#include "datamonitor.h"
#include "core/databasepool/databasepool.h"
#include <QSqlQuery>
#include <QVariant>
#include <QDebug>
#include <QSqlError>
#include <QDateTime>

// 创建数据表（增强外键约束）
void DataMonitor::createDataTable() {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.exec(R"(
        CREATE TABLE IF NOT EXISTS data (
            data_id INTEGER PRIMARY KEY AUTOINCREMENT,
            device_id INTEGER NOT NULL,
            timestamp TEXT NOT NULL,
            temperature REAL,
            humidity REAL,
            light REAL,
            co2 REAL,
            pressure REAL,
            FOREIGN KEY (device_id) REFERENCES devices(device_id) ON DELETE CASCADE
        )
    )");
    DatabasePool::instance().releaseConnection(db);
}

DataMonitor::DataMonitor(QObject* parent) : QObject(parent) {
    createDataTable();
    m_timer.setInterval(1000);
    connect(&m_timer, &QTimer::timeout, this, &DataMonitor::onTimerTimeout);
}

DataMonitor::~DataMonitor() {}

void DataMonitor::startMonitoring() { m_timer.start(); }
void DataMonitor::stopMonitoring() { m_timer.stop(); }

// 插入数据（严格校验设备存在性）
bool DataMonitor::receiveAndStoreData(int deviceId, double temperature, double humidity,
                                    double light, double co2, double pressure) {
    if (deviceId <= 0) {
        qDebug() << "[错误] 设备ID必须为正整数";
        return false;
    }

    // 检查设备是否存在
    QSqlDatabase checkDb = DatabasePool::instance().getConnection();
    checkDb.exec("PRAGMA foreign_keys = ON;");
    QSqlQuery checkQuery(checkDb);
    checkQuery.prepare("SELECT 1 FROM devices WHERE device_id = ?");
    checkQuery.addBindValue(deviceId);
    if (!checkQuery.exec() || !checkQuery.next()) {
        qDebug() << "[错误] 设备ID" << deviceId << "不存在";
        DatabasePool::instance().releaseConnection(checkDb);
        return false;
    }
    DatabasePool::instance().releaseConnection(checkDb);

    // 插入数据
    QSqlDatabase db = DatabasePool::instance().getConnection();
    db.exec("PRAGMA foreign_keys = ON;");
    QSqlQuery query(db);
    query.prepare("INSERT INTO data (device_id, timestamp, temperature, humidity, light, co2, pressure) "
                  "VALUES (?, ?, ?, ?, ?, ?, ?)");
    query.addBindValue(deviceId);
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    query.addBindValue(timestamp);
    query.addBindValue(temperature);
    query.addBindValue(humidity);
    query.addBindValue(light);
    query.addBindValue(co2);
    query.addBindValue(pressure);

    if (!query.exec()) {
        qDebug() << "插入失败：" << query.lastError().text();
        DatabasePool::instance().releaseConnection(db);
        return false;
    }
    qDebug() << "成功插入数据，设备ID:" << deviceId << "，时间戳:" << timestamp;
    emit newDataAvailable(deviceId, temperature, humidity, light, co2, pressure);
    DatabasePool::instance().releaseConnection(db);
    return true;
}

// 查询历史数据（动态构造SQL）
QList<QSqlRecord> DataMonitor::queryHistoricalData(int deviceId,
                                                 const QString& startTime,
                                                 const QString& endTime) {
    QList<QSqlRecord> dataRecords;
    QSqlDatabase db = DatabasePool::instance().getConnection();
    db.exec("PRAGMA foreign_keys = ON;");
    QSqlQuery query(db);

    QString sql = "SELECT * FROM data WHERE timestamp BETWEEN ? AND ?";
    if (deviceId > 0) sql += " AND device_id = ?";

    query.prepare(sql);
    query.addBindValue(startTime);
    query.addBindValue(endTime);
    if (deviceId > 0) query.addBindValue(deviceId);

    if (query.exec()) {
        while (query.next()) {
            dataRecords.append(query.record());
        }
        qDebug() << "查询到" << dataRecords.size() << "条记录";
    } else {
        qDebug() << "查询失败：" << query.lastError().text();
    }
    DatabasePool::instance().releaseConnection(db);
    return dataRecords;
}

// 定时器数据更新（查询最新数据）
void DataMonitor::onTimerTimeout() {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    db.exec("PRAGMA foreign_keys = ON;");
    QSqlQuery query(db);
    // 修改查询条件为前一小时内的数据
    query.prepare("SELECT device_id, temperature, humidity, light, co2, pressure "
                  "FROM data WHERE timestamp > datetime('now', '-1 hour')");
    if (query.exec()) {
        int rowCount = 0;
        while (query.next()) {
            rowCount++;
            int deviceId = query.value(0).toInt();
            double temperature = query.value(1).toDouble();
            double humidity = query.value(2).toDouble();
            double light = query.value(3).toDouble();
            double co2 = query.value(4).toDouble();
            double pressure = query.value(5).toDouble();
            emit newDataAvailable(deviceId, temperature, humidity, light, co2, pressure);
            qDebug() << "Emitted newDataAvailable signal for device ID:" << deviceId;
        }
        qDebug() << "Query found" << rowCount << "records.";
    } else {
        qDebug() << "实时数据查询失败：" << query.lastError().text();
    }
    DatabasePool::instance().releaseConnection(db);
}
